package com.zyf.larklaunch.v1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 顶层入口类
 * @author yifeng
 */
public class DarkLaunch {
    private static final Logger log = LoggerFactory.getLogger(DarkLaunch.class);
    private static final int DEFAULT_RULE_UPDATE_TIME_INTERVAL = 60; // in secondary
    private DarkRule rule;
    private ScheduledExecutorService executor;

    public DarkLaunch(int ruleUpdateTimeInterval) {
        loadRule();
        this.executor = Executors.newSingleThreadScheduledExecutor();
        this.executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                loadRule();
            }
        }, ruleUpdateTimeInterval, ruleUpdateTimeInterval, TimeUnit.SECONDS);
    }

    public DarkLaunch() {
        this(DEFAULT_RULE_UPDATE_TIME_INTERVAL);
    }

    private void loadRule() {
        // 将灰度规则配置文件 dark-rule.yaml 中的内容读取 DarkRuleConfig 中
        DarkRuleConfig ruleConfig = null;
        try(InputStream in = this.getClass().getResourceAsStream("/dark-rule.yaml")) {
             if (in != null) {
                 Yaml yaml = new Yaml();
                 ruleConfig = yaml.loadAs(in, DarkRuleConfig.class);
             }
        } catch (IOException e) {
            log.error("close file error:{}", e);
        }

        if (ruleConfig == null) {
            throw new RuntimeException("Can not load dark rule.");
        }

        DarkRule newRule = new DarkRule(ruleConfig);
        this.rule = newRule;
    }

    public DarkFeature getDarkFeature(String featureKey) {
        return this.rule.getDarkFeature(featureKey);
    }
}
